﻿using System;
using System.Collections.Generic;
using RssReader.Common;
using RssReader.FeedProvider;
using Windows.ApplicationModel.DataTransfer;
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Item Detail Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234232

namespace RssReader
{
    /// <summary>
    /// A page that displays details for a single selectedItem within a group while allowing gestures to
    /// flip through other items belonging to the same group.
    /// </summary>
    public sealed partial class ItemDetailPage : LayoutAwarePage
    {
        private static TypedEventHandler<DataTransferManager, DataRequestedEventArgs> _handler;

        static private Dictionary<string, object> _sessionState = new Dictionary<string, object>();
        private static Type _previousFrame;
        static public Dictionary<string, object> Session_state
        {
            get { return _sessionState; }
        }
        public ItemDetailPage()
        {
            this.InitializeComponent();

            NavigationCacheMode = NavigationCacheMode.Enabled;

            if (_handler != null)
                DataTransferManager.GetForCurrentView().DataRequested -= _handler;


            _handler = Data_requested;
            DataTransferManager.GetForCurrentView().DataRequested += _handler;
        }

        
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            const string pageStateKey = "itemdetail";

            var frameState = SuspensionManager.SessionState;
            if (navigationParameter !=null)
            {
                frameState[pageStateKey] = navigationParameter;
            }

            if (frameState != null && frameState.ContainsKey(pageStateKey)) navigationParameter = frameState[pageStateKey];

            MainGrid.Background = new SolidColorBrush(App.ARGBColor);

            var tuple = (Tuple<string, Dictionary<string, object>,Type>)navigationParameter;
            if (tuple != null)
            {
                var selectedItem = tuple.Item1;
                _sessionState = tuple.Item2;
                _previousFrame = tuple.Item3;
                Get_feed(selectedItem);
            }
        }
        
        private async void Get_feed(string selectedItem)
        {
            var selectedFeed = Session_state[App.ItemsKeyString] as Feed;
            if (selectedFeed != null)
            {
                flipView.ItemsSource = selectedFeed.Items;
                Set_item_index(selectedItem, selectedFeed);
            }
        }

        private void Set_item_index(string selectedItem, Feed selectedFeed)
        {
            int itemIndex = 0;
            foreach (Item listItem in selectedFeed.Items)
            {
                if (listItem.Title == selectedItem)
                {
                    break;
                }
                itemIndex++;
            }
            this.flipView.SelectedIndex = itemIndex;
        }

        /// <summary>
        /// Invoked when the back button is pressed.
        /// </summary>
        /// <param name="sender">The Button instance representing the back button.</param>
        /// <param name="e">Event data describing how the button was clicked.</param>
        protected override void GoBack(object sender, RoutedEventArgs e)
        {
            // Return the application to the state it was in before search results were requested

            if (_previousFrame == null) _previousFrame = typeof(ItemsPage);

            var rootFrame = new Frame();
            rootFrame.Navigate(_previousFrame);

            // Place the frame in the current Window and ensure that it is active
            Window.Current.Content = rootFrame;
        }

        private void Readmore_OnClick(object sender, RoutedEventArgs e)
        {
            var item = (Item)flipView.SelectedItem;
            var link = item.Links[0].Url;
            Windows.System.Launcher.LaunchUriAsync(new Uri(link));
        }

        async void Data_requested(DataTransferManager sender, DataRequestedEventArgs e)
        {
            var item = (Item) this.flipView.SelectedItem;
            e.Request.Data.Properties.Title = "Shared from Windows 8 RSS Reader: " + item.Title;
            var description = "Windows 8 RSS Reader would like to share this with you " + Environment.NewLine + item.Links[0].Url;
            e.Request.Data.Properties.Description = description;
            e.Request.Data.SetText(description);

        }

    }   
}
